// audioList/index.js
import audioManager from '../../utils/audioManager.js'

Page({
  data: {
    audioList: [],
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0,
      hasMore: true
    },
    loading: false,
    refreshing: false,
    loadingMore: false,
    keyword: '',
    category: ''
  },

  onLoad(options) {
    // 获取页面参数
    if (options.category) {
      this.setData({
        category: options.category
      })
    }
    
    // 初始化加载数据
    this.loadAudioList(true)
  },

  onShow() {
    // 页面显示时不重复加载数据
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.setData({
      refreshing: true
    })
    this.loadAudioList(true)
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.pagination.hasMore && !this.data.loadingMore) {
      this.loadMoreAudio()
    }
  },

  /**
   * 加载音频列表
   * @param {boolean} refresh - 是否刷新（重置分页）
   */
  loadAudioList(refresh = false) {
    if (refresh) {
      this.setData({
        'pagination.page': 1,
        'pagination.hasMore': true,
        loading: true
      })
    }

    const { page, pageSize } = this.data.pagination
    const { keyword, category } = this.data

    wx.cloud.callFunction({
      name: 'fetchAudio',
      data: {
        type: 'getAudioList',
        page: page,
        pageSize: pageSize,
        keyword: keyword || undefined,
        category: category || undefined,
        orderBy: '_createTime',
        order: 'desc'
      }
    }).then(res => {
      console.log('获取音频列表结果:', res)
      
      if (res.result && res.result.success) {
        const { list, pagination } = res.result.data
        
        this.setData({
          audioList: refresh ? list : [...this.data.audioList, ...list],
          'pagination.page': pagination.page,
          'pagination.total': pagination.total,
          'pagination.hasMore': pagination.hasMore,
          loading: false,
          refreshing: false,
          loadingMore: false
        })

        // 停止下拉刷新
        if (refresh) {
          wx.stopPullDownRefresh()
          if (list.length === 0) {
            wx.showToast({
              title: '暂无音频数据',
              icon: 'none'
            })
          }
        }
      } else {
        this.handleError(res.result ? res.result.errMsg : '获取数据失败')
      }
    }).catch(err => {
      console.error('调用云函数失败:', err)
      this.handleError('网络请求失败，请检查网络连接')
    })
  },

  /**
   * 加载更多音频
   */
  loadMoreAudio() {
    this.setData({
      loadingMore: true,
      'pagination.page': this.data.pagination.page + 1
    })
    
    this.loadAudioList(false)
  },

  /**
   * 处理错误
   */
  handleError(message) {
    this.setData({
      loading: false,
      refreshing: false,
      loadingMore: false
    })
    
    wx.stopPullDownRefresh()
    wx.showToast({
      title: message,
      icon: 'none',
      duration: 2000
    })
  },

  /**
   * 搜索音频
   */
  onSearchInput(e) {
    this.setData({
      keyword: e.detail.value
    })
  },

  onSearchConfirm() {
    this.loadAudioList(true)
  },

  /**
   * 清空搜索
   */
  onClearSearch() {
    this.setData({
      keyword: ''
    })
    this.loadAudioList(true)
  },

  /**
   * 点击音频项
   */
  onAudioTap(e) {
    const { id } = e.currentTarget.dataset
    const audio = this.data.audioList.find(item => item._id === id)
    
    if (audio) {
      // 设置播放列表到全局管理器
      const currentIndex = this.data.audioList.findIndex(item => item._id === id)
      audioManager.setPlaylist(this.data.audioList, currentIndex)
      
      // 跳转到音频播放页面
      const playlist = encodeURIComponent(JSON.stringify(this.data.audioList))
      
      wx.navigateTo({
        url: `/pages/audioPlayer/index?audioId=${id}&playlist=${playlist}&index=${currentIndex}`
      })
    }
  },

  /**
   * 获取音频详情
   */
  getAudioDetail(audioId) {
    wx.showLoading({
      title: '加载中...'
    })

    wx.cloud.callFunction({
      name: 'fetchAudio',
      data: {
        type: 'getAudioDetail',
        audioId: audioId
      }
    }).then(res => {
      wx.hideLoading()
      
      if (res.result && res.result.success) {
        const audioDetail = res.result.data
        
        // 这里可以跳转到音频详情页面或者直接播放
        wx.showModal({
          title: audioDetail.title || '音频详情',
          content: `时长: ${audioDetail.duration || '未知'}\n大小: ${audioDetail.size || '未知'}\n格式: ${audioDetail.format || '未知'}`,
          showCancel: true,
          cancelText: '取消',
          confirmText: '播放',
          success: (modalRes) => {
            if (modalRes.confirm) {
              this.playAudio(audioDetail)
            }
          }
        })
      } else {
        wx.showToast({
          title: '获取音频详情失败',
          icon: 'none'
        })
      }
    }).catch(err => {
      wx.hideLoading()
      console.error('获取音频详情失败:', err)
      wx.showToast({
        title: '网络请求失败',
        icon: 'none'
      })
    })
  },

  /**
   * 播放音频
   */
  playAudio(audioDetail) {
    if (audioDetail.url) {
      // 使用微信小程序的音频播放API
      const audioContext = wx.createInnerAudioContext()
      audioContext.src = audioDetail.url
      audioContext.title = audioDetail.title
      
      audioContext.onPlay(() => {
        wx.showToast({
          title: '开始播放',
          icon: 'success'
        })
      })
      
      audioContext.onError((res) => {
        console.error('音频播放失败:', res)
        wx.showToast({
          title: '播放失败',
          icon: 'none'
        })
      })
      
      audioContext.play()
    } else {
      wx.showToast({
        title: '音频文件不存在',
        icon: 'none'
      })
    }
  },

  /**
   * 添加到播放列表
   */
  addToPlaylist(e) {
    const { id } = e.currentTarget.dataset
    const audio = this.data.audioList.find(item => item._id === id)
    
    if (audio) {
      const success = audioManager.addToPlaylist(audio)
      
      if (success) {
        wx.showToast({
          title: '已添加到播放列表',
          icon: 'success',
          duration: 1500
        })
      } else {
        wx.showToast({
          title: '已在播放列表中',
          icon: 'none',
          duration: 1500
        })
      }
    }
  },

  /**
   * 阻止事件冒泡
   */
  preventBubble() {
    // 阻止点击事件冒泡到父元素
  }
})
